package com.xoa.service.attend;

import com.xoa.dao.attend.AttendOutMapper;
import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dao.workflow.FlowRunMapper;
import com.xoa.dao.workflow.FlowRunPrcsMapper;
import com.xoa.model.attend.AttendEvectionFlowRunPrcs;
import com.xoa.model.attend.AttendOut;
import com.xoa.model.attend.AttendOutFlowRunPrcs;
import com.xoa.model.common.SysCode;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.FlowFast;
import com.xoa.model.workflow.FlowRun;
import com.xoa.model.workflow.FlowRunPrcs;
import com.xoa.service.WFE.WFERunner.WFEFlowRunInfo;
import com.xoa.service.work.WorkService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.DateCompute;
import com.xoa.util.DateFormat;
import com.xoa.util.ToJson;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.common.wrapper.BaseWrappers;
import com.xoa.util.ipUtil.IpAddr;
import com.xoa.util.page.PageParams;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by gsb on 2017/7/17.
 */
@Service
public class AttendOutService {

    @Autowired
    private AttendOutMapper attendOutMapper;//外出
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private FlowRunPrcsMapper flowRunPrcsMapper;
    @Autowired
    private FlowRunMapper flowRunMapper;
    @Autowired
    private SysCodeMapper sysCodeMapper;
    @Autowired
    private WFEFlowRunInfo wfeFlowRunInfo;


    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017-7-14 下午14:45:00
     * 方法介绍:   查询外出登记
     */
    public ToJson<AttendOutFlowRunPrcs> queryAllAttendOut(Integer page, Integer pageSize,
                                               Boolean useFlag,HttpServletRequest request,String FlowAllow){
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        Map<String, Object> objectMap = new HashMap<String, Object>();
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        objectMap.put("page", pageParams);
        objectMap.put("userId", users.getUserId());
        objectMap.put("flowAllow",FlowAllow);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ToJson<AttendOutFlowRunPrcs> json = new ToJson<AttendOutFlowRunPrcs>(1, "error");
        try{
            List<AttendOutFlowRunPrcs> attendOutList=attendOutMapper.queryAllAttendOut(objectMap);
            for (AttendOut attendOut:attendOutList){
                String date= DateFormat.getDatestr(attendOut.getCreateDate()).substring(0,10);
                if(!StringUtils.checkNull(attendOut.getUserId())) {
                    if(usersMapper.findUsersByuserId(attendOut.getUserId())!=null){
                        attendOut.setUserName(usersMapper.findUsersByuserId(attendOut.getUserId()).getUserName());
                    }
                    if(usersMapper.findUsersByuserId(attendOut.getUserId())!=null){
                        attendOut.setDeptName(departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(attendOut.getUserId()).getDeptId()));
                    }
                }

                if(!StringUtils.checkNull(attendOut.getAgent())){
                    if(usersMapper.findUsersByuserId(attendOut.getAgent())!=null){
                        attendOut.setAgent(usersMapper.findUsersByuserId(attendOut.getAgent()).getUserName());
                    }
                }
               if(!StringUtils.checkNull(attendOut.getStatus())){
                   int status=Integer.valueOf(attendOut.getStatus());
                   switch (status){
                       case 1:
                           attendOut.setStatus("未确认");
                           break;
                       case 2:
                           attendOut.setStatus("确认归来");
                           break;
                   }
               }
                if(!StringUtils.checkNull(attendOut.getAllow())){
                    int allow=Integer.valueOf(attendOut.getAllow());
                    switch (allow){
                        case 0:
                            attendOut.setAllow("待审批");
                            break;
                        case 1:
                            attendOut.setAllow("已批准");
                            break;
                        case 2:
                            attendOut.setAllow("未批准");
                            break;
                    }
                }

                if(!StringUtils.checkNull(attendOut.getOutTime1())&&!StringUtils.checkNull(attendOut.getOutTime2())){

                    Date outTime1=DateFormat.getDate(attendOut.getOutTime1());
                    Date outTime2=DateFormat.getDate(attendOut.getOutTime2());
                    long begin=DateFormat.getTime(sdf.format(outTime1));
                    long end=DateFormat.getTime(sdf.format(outTime2));
                    attendOut.setOutTime(DateFormat.returnTime((int)(end-begin)));
                    attendOut.setOutTime1(attendOut.getOutTime1());
                    attendOut.setOutTime2(attendOut.getOutTime2());
                }else {
                    attendOut.setOutTime("");
                    attendOut.setOutTime1("");
                    attendOut.setOutTime2("");
                }

                FlowRunPrcs flowRunPrcs= flowRunPrcsMapper.queryByRunId(attendOut.getRunId());
                if(flowRunPrcs!=null){
                    attendOut.setFlowPrcs(flowRunPrcs.getFlowPrcs().toString());
                    attendOut.setPrcsId(flowRunPrcs.getPrcsId().toString());
                }else {
                    attendOut.setFlowPrcs("");
                    attendOut.setPrcsId("");
                }
                FlowRun flowRun=flowRunMapper.find(attendOut.getRunId());
                if(flowRun!=null){
                    attendOut.setRunId(flowRun.getRunId());
                }

            }

            json.setObj(attendOutList);
            json.setMsg("ok");
            json.setFlag(0);
            json.setTotleNum(pageParams.getTotal());
        }catch(Exception e){
            json.setMsg(e.getMessage());
            L.e("AttendService queryAllAttendOut:"+e);
        }
        return  json;
    }
    public BaseWrapper addAllAttendOut( String createDate, HttpServletRequest request){
        BaseWrapper baseWrapper=new BaseWrapper();
        AttendOut attendOut=new AttendOut();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        String  sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        List<SysCode>  SysCode= sysCodeMapper.getSysCode("KQQJTYPE");
        for(SysCode sysCode:SysCode){
            if(sysCode.getCodeName().equals("外出申请")){
                ToJson<FlowFast> flowFastToJson=  wfeFlowRunInfo.workFastAdd(users, Integer.parseInt(sysCode.getCodeNo()) ,1,"1","",request,sqlType,"",null);
                if(flowFastToJson.isFlag()){
                     FlowFast flowFast=(FlowFast)flowFastToJson.getObject();
                    attendOut.setUserId(users.getUserId());
                    attendOut.setUserName(users.getUserName());
                    attendOut.setCreateDate(DateFormat.getDate(createDate));
                    attendOut.setSubmitTime(DateFormat.getDate(createDate));
                    attendOut.setRegisterIp(IpAddr.getIpAddress(request));
                    attendOut.setRunId(flowFast.getFlowRun().getRunId());
                    attendOut.setStatus("1");
                    attendOut.setTableName("attend_out");
                    attendOut.setAllow("0");

                    int amount=attendOutMapper.insertSelective(attendOut);
                    if(amount>0){
                        attendOut.setFlowId(flowFast.getFlowTypeModel().getFlowId().toString());
                        attendOut.setFlowName(flowFast.getFlowTypeModel().getFlowName());
                        baseWrapper.setFlag(true);
                        baseWrapper.setStatus(true);
                        baseWrapper.setData(attendOut);
                        baseWrapper.setMsg("更新成功");
                    }
                }
            }

        }







        return  baseWrapper;
    }


    public BaseWrappers backlogAttendList(HttpServletRequest request, String num, Integer page, Integer pageSize,
                                          Boolean useFlag){
        BaseWrappers wrappers =new BaseWrappers();
        wrappers.setStatus(true);
        wrappers.setFlag(false);
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users =SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        if(StringUtils.checkNull(users.getUserId())){
            wrappers.setMsg("用户信息过期");
            return wrappers;
        }
        Map<String,Object> map=new HashMap<String,Object>();
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        map.put("page", pageParams);
        map.put("userId", users.getUserId());
        wrappers.setTotal(pageParams.getTotal());
        if("1".equals(num)){
            List<AttendOutFlowRunPrcs> attendFlowRunPrcs=attendOutMapper.backlogAttendOut(map);
            for(AttendOutFlowRunPrcs attendFlowRunPrcs1:attendFlowRunPrcs){
                String date= DateFormat.getDatestr(attendFlowRunPrcs1.getCreateDate()).substring(0,9);
                if(!StringUtils.checkNull(attendFlowRunPrcs1.getUserId())) {
                    if(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId())!=null){
                        attendFlowRunPrcs1.setUserName(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId()).getUserName());
                    }
                    if(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId())!=null){
                        attendFlowRunPrcs1.setDeptName(departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId()).getDeptId()));
                    }
                }

                attendFlowRunPrcs1.setTableName("attend_out");
            }
            wrappers.setFlag(true);
            wrappers.setDatas(attendFlowRunPrcs);
            wrappers.setTotal(pageParams.getTotal());
        }else if("2".equals(num)) {
            List<AttendOutFlowRunPrcs> attendFlowRunPrcs=attendOutMapper.haveDoneAttendOut(map);
            for(AttendOutFlowRunPrcs attendFlowRunPrcs1:attendFlowRunPrcs){
                String date= DateFormat.getDatestr(attendFlowRunPrcs1.getCreateDate()).substring(0,9);
                if(!StringUtils.checkNull(attendFlowRunPrcs1.getUserId())) {
                    if(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId())!=null){
                        attendFlowRunPrcs1.setUserName(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId()).getUserName());
                    }
                    if(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId())!=null){
                        attendFlowRunPrcs1.setDeptName(departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId()).getDeptId()));
                    }
                }

                attendFlowRunPrcs1.setTableName("attend_out");
            }
            wrappers.setFlag(true);
            wrappers.setDatas(attendFlowRunPrcs);
            wrappers.setTotal(pageParams.getTotal());
        }

        return  wrappers;
    }
    /**
     * 创建人：季佳伟
     * 创建时间：2017-11-21  下午5:30:17
     * 方法介绍：查询登录人一段时间内的外出状况
     * 参数说明：
     */
    public ToJson<AttendOut> queryAttendOutByUserId(String beginDate, String endDate,HttpServletRequest req){
        ToJson<AttendOut> json = new ToJson<AttendOut>();
        try {
            Cookie redisSessionId = CookiesUtil.getCookieByName(req, "redisSessionId");
            String userId = SessionUtils.getSessionInfo(req.getSession(), Users.class, new Users(),redisSessionId).getUserId();
            List<Date> dates = DateCompute.getBetweenDates(DateFormat.DateToStr(beginDate), DateFormat.DateToStr(endDate));
            List<AttendOut> attendOutList = attendOutMapper.queryAttendOutByUserId(userId);
            List<AttendOut> newAttendOutList = new ArrayList<AttendOut>();
            if(attendOutList.size() >0){
               for (AttendOut attendOut : attendOutList){
                   for (Date nowDate : dates){
                       String aTime = DateFormat.getDatestr(attendOut.getSubmitTime()).substring(0,10);
                       String nTime = DateFormat.getDatestr(nowDate);
                       if(aTime.equals(nTime)){

                           newAttendOutList.add(attendOut);

                       }
                   }
               }
               json.setObj(newAttendOutList);
               json.setFlag(0);
               json.setMsg("ok");

            }else {
                json.setFlag(1);
                json.setMsg("err");
            }

        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg("err");
        }

        return json;
    }

}
